#!/bin/sh
set -e

add_groups()
{
    if ! getent group iotedge >/dev/null; then
        groupadd -r iotedge
    fi

    if ! getent passwd iotedge >/dev/null; then
        useradd -r -g iotedge -c 'iotedge user' -s /sbin/nologin -d /var/lib/aziot/edged iotedge
    fi
    mkdir -p /var/lib/aziot/edged

    # Create an edgeagentuser and add it to iotedge group
    if ! getent passwd edgeagentuser >/dev/null; then
        useradd -r -g iotedge -c "edgeAgent user" -s /sbin/nologin -u 13622 edgeagentuser || true
    fi

    # Create an edgehubuser
    if ! getent passwd edgehubuser >/dev/null; then
        useradd -r -c "edgeHub user" -s /sbin/nologin -u 13623 edgehubuser || true
    fi

    # add iotedge user to docker group so that it can talk to the docker socket
    if getent group docker >/dev/null; then
        usermod -aG docker iotedge
    fi

     # add iotedge user to systemd-journal group so it can get system logs
    if getent group systemd-journal >/dev/null; then
        usermod -aG systemd-journal iotedge
    fi

    if getent group aziotcs >/dev/null; then
        usermod -aG aziotcs iotedge
    fi
    if getent group aziotks >/dev/null; then
        usermod -aG aziotks iotedge
    fi
    if getent group aziotid >/dev/null; then
        usermod -aG aziotid iotedge
    fi

    # Add each admin user to the iotedge group - for systems installed before precise
    for u in $(getent group admin | sed -e "s/^.*://" -e "s/,/ /g"); do
        usermod -aG iotedge "$u" >/dev/null || true
    done

    # Add each sudo user to the iotedge group
    for u in $(getent group sudo | sed -e "s/^.*://" -e "s/,/ /g"); do
        usermod -aG iotedge "$u" >/dev/null || true
    done
}

check_runtime()
{
    # Verify a container runtime exists before installing.

    if ! getent group docker >/dev/null; then
        echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
        echo ""
        echo " ERROR: No container runtime detected."
        echo ""
        echo " Please install a container runtime and run this install again."
        echo ""
        echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"

        exit 1
    fi
}

case "$1" in
    install|upgrade)
        check_runtime
        add_groups
    ;;

    abort-upgrade)
    ;;

    *)
        echo "preinst called with unknown argument \`$1'" >&2
        exit 1
    ;;
esac


#DEBHELPER#

exit 0
